/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddContact.java
 *
 * Created on Jan 11, 2013, 2:57:33 AM
 */
package view;

import java.awt.Color;
import java.rmi.RemoteException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import controller.ClientController;
import dto.Account;
import java.util.Vector;
import javax.swing.JOptionPane;

/**
 *
 * @author BLACK
 */
public class AddContact extends javax.swing.JFrame implements Runnable {

    /**
     * 
     */
    private static final long serialVersionUID = -3153590114419873428L;

    /** 
     * Creates new form AddContact 
     */
   /** 
     * Add contact Frame is to help user to add new contact by typing it's mail
     * then server checks that user and send Friend request after some validation.
     * [1]. No Duplication. user can't add the same friend twice.
     * [2]. user can't add himself/herself.
     * [3]. mail should be valid.
     * 
     */
    public AddContact() {
        initComponents();
    }
    MainFrame mainFrameRef;
    ClientController controller;

    public AddContact(MainFrame mainFrameRef, ClientController controller) {

        initComponents();
        this.mainFrameRef = mainFrameRef;
        this.controller = controller;

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 18));
        jLabel1.setText("Enter New Contact Info:");

        jLabel2.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        jLabel2.setText("Email Address:");

        jButton1.setText("Add to Contact List");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Times New Roman", 0, 14));
        jLabel3.setText("ex: JohnAdam@gmail.com");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 191, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(20, 20, 20)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jTextField1, javax.swing.GroupLayout.DEFAULT_SIZE, 290, Short.MAX_VALUE)))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(107, 107, 107)
                        .addComponent(jButton1)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 21, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addComponent(jButton1)
                .addGap(27, 27, 27))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**
     * validateEmail method checks if the mail is valid.
     */
    public boolean validateEmail(String mail) {

        String EMAIL_PATTERN =
                "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
                + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

        Boolean isValidEMail = true;
        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(mail);

        if (!matcher.matches()) {
            isValidEMail = false;
        }
        return isValidEMail;
    }
    /**
     * ActionListener to add_Button, that made some validaton on the new contact
     * & if it'ok .. Send request to server in thread. 
     */
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        String contactAdd = jTextField1.getText();
        Boolean ret = validateEmail(contactAdd);
        String confirmation = "Friend Request has been sent Successfully.";

        if (ret) {
            Boolean alreadyExist = false;
            Vector<Account> contactList = mainFrameRef.sendContactList();

            if (contactAdd.equalsIgnoreCase(controller.getLoggedInAccount().getEmail())) {
                confirmation = "Sorry, But you can't add yourself to contact List!";
            } else {
                if (contactList != null) {
                    for (int i = 0; i < contactList.size(); i++) {
                        if (contactAdd.equalsIgnoreCase(contactList.get(i).getEmail())) {
                            alreadyExist = true;
                            confirmation = "This contact is already exists in your contact list.";
                            break;
                        }
                    }
                }

                if (!alreadyExist) {
                    Thread th = new Thread(this);
                    th.start();
                }
            }

            JOptionPane.showMessageDialog(this, confirmation);
            controller.setActiveWindow(mainFrameRef);
            this.setVisible(false);
        } else {
            jTextField1.setForeground(Color.red);
        }

    }//GEN-LAST:event_jButton1ActionPerformed

    @Override
    public void run() {
        String contactAdd = jTextField1.getText();

        try {

            ClientController.getService().addContact(contactAdd, controller.getLoggedInAccount());

        } catch (RemoteException ex) {
            Logger.getLogger(AddContact.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new AddContact().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
